package com.whut.customer.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whut.common.util.R;
import com.whut.customer.base.BaseController;
import com.whut.customer.entity.SysRole;
import com.whut.customer.service.ISysRoleService;
import com.whut.customer.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author author
 * @since 2021-01-23
 */
@RestController
@RequestMapping("/sysRole")
public class SysRoleController extends BaseController {

    @Autowired
    ISysRoleService roleService;

    @ApiOperation("添加角色")
    @PostMapping("/addRole")
    public R addRole(@RequestBody SysRole role) {
        if(StringUtil.isNull(role.getRoleName()))
            return R.failed("角色名不能为空!");
        LambdaQueryWrapper<SysRole> eq = new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleName, role.getRoleName())
                .eq(SysRole::getDelFlag, 0);
        List<SysRole> roleList = roleService.list(eq);
        if (!CollectionUtils.isEmpty(roleList))
            return R.failed("该角色已存在!");
        return  R.ok(roleService.save(role));
    }

    @ApiOperation("修改角色")
    @PostMapping("/updateRole")
    public R updateRole(@RequestBody SysRole role) {
        if(role.getId() == null || StringUtil.isNull(role.getRoleName()))
            return R.failed("id或角色名不能为空!");
        LambdaQueryWrapper<SysRole> eq = new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleName, role.getRoleName())
                .eq(SysRole::getDelFlag, 0);
        List<SysRole> roleList = roleService.list(eq);
        if (!CollectionUtils.isEmpty(roleList))
            return R.failed("该角色已存在!");
        return R.ok(roleService.saveOrUpdate(role));
    }

    @ApiOperation("查找角色")
    @PostMapping("/selectRole")
    public R<List<SysRole>> selectRole(@RequestBody SysRole role) {
        LambdaQueryWrapper<SysRole> eq = new LambdaQueryWrapper<SysRole>()
                .eq(role.getId() !=null, SysRole::getId, role.getId())
                .eq(role.getRoleName() != null, SysRole::getRoleName, role.getRoleName())
                .eq(SysRole::getDelFlag, 0);
        return R.ok(roleService.list(eq));
    }

    @ApiOperation("删除角色")
    @PostMapping("/deleteRoleById")
    public R deleteRoleById(@PathVariable Long roleId) {
        return R.ok(roleService.removeById(roleId));
    }

}
